(function() {
    'use strict';

    /**
     * @ngdoc directive
     * @name webApp.directive:rolelist
     * @description
     * # rolelist 
     */
    angular.module('webApp')

    .directive('importExcel', ['dataService', '$compile', function(dataService, $compile) {
        return {
            restrict: 'E',
            // require: 'ngModel',
            replace: true,
            scope: {
                type: "@"
            },

            templateUrl: "views/directives.importexcel.html",
            controller: ['$templateCache', '$rootScope', '$scope', '$timeout', 'sku', 'helper', 'ERP_CONFIG', function($templateCache, $rootScope, $scope, $timeout, sku, helper, ERP_CONFIG) {

                var wb; //读取完成的数据
                var rABS = false; //是否将文件读取为二进制字符
                $scope.store = $rootScope.store_id;
                $scope.records = {};
                $scope.savetype = 0;
                $scope.odj = null;
                $scope.mb = ERP_CONFIG.webUrl + '/web/dhfshop/app/images/mb.xlsx';
                $scope.importf = function(obj, $event) {
                    if (!obj) {
                        return;
                    }
                    $scope.odj = obj;
                    var f = obj;
                    var reader = new FileReader();
                    reader.onload = function(e) {
                        var data = e.target.result;
                        if (rABS) {
                            wb = XLSX.read(btoa(fixdata(data)), { //手动转化
                                type: 'base64'
                            });
                        } else {
                            wb = XLSX.read(data, {
                                type: 'binary'
                            });
                        }
                        $timeout(function() {
                            var records = JSON.stringify(XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]));
                            // console.error("records", records);
                            //找到对应的商品类目id
                            $scope.getcategory(JSON.parse(records), $event);
                        });
                    };
                    if (rABS) {
                        reader.readAsArrayBuffer(f);
                    } else {
                        reader.readAsBinaryString(f);
                    }
                }

                function fixdata(data) { //文件流转BinaryString
                    var o = "",
                        l = 0,
                        w = 10240;
                    for (; l < data.byteLength / w; ++l) o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)));
                    o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)));
                    return o;
                }

                $scope.getcategory = function(records, $event) {
                    records.splice(0, 1);
                    if (!records[0].category || !records[0].outer_id || !records[0].sku_price || !records[0].sku_outer_id || !records[0].spec1 || !records[0].attribute1) {
                        helper.myAlert("导入数据格式错误，请按照要求填写数据!");
                        $scope.odj = null;
                        return false;
                    }
                    var query = {
                        content: {
                            pickpoint_id: records[0].delivery_addrs,
                            store_id: $scope.store_id
                        }
                    };
                    dataService.pickpointGet(query, true).then(function(list) {
                        if (list.total_count == 0) {
                            helper.myAlert("请填属于当前商户仓库地址！");
                            return false;
                        }
                    });
                    var cateData = {};
                    $scope.newData = {};
                    _.map(records, function(data, ky) {
                        if (data.category && data) {
                            cateData[data.category] = data.category;
                            data.on_shelves = 1; //状态
                            data.store_id = $scope.store;
                            data.status = 0; //状态
                            data.price = parseFloat(data.sku_price);
                            data.is_incl_postage = 1; //是否包邮
                            var sku_pr = "1:1:" + data.spec1 + ":" + data.attribute1 + ";";
                            if (data.spec2 && data.attribute2) {
                                sku_pr += "1:1:" + data.spec2 + ":" + data.attribute2 + ";";
                            }
                            if (data.spec3 && data.attribute3) {
                                sku_pr += "1:1:" + data.spec3 + ":" + data.attribute3 + ";";
                            }
                            var sku = {
                                "sku_outer_id": data.sku_outer_id,
                                "sku_properties": sku_pr,
                                "sku_price": parseFloat(data.sku_price),
                                "sku_stocks": parseInt(data.sku_stocks),
                                "status_id": 1,
                                "barcode": data.barcode,
                                "imgurl": data.imgurl
                            };
                            if (!$scope.newData) {
                                data.skus = [sku];
                                $scope.newData[data.outer_id] = data;
                            } else {
                                if ($scope.newData[data.outer_id]) {
                                    $scope.newData[data.outer_id]['skus'].push(sku);
                                } else {
                                    data.skus = [sku];
                                    $scope.newData[data.outer_id] = data;
                                }
                            }
                        } else {
                            records.splice(ky, 1);
                        }
                    });

                    if (cateData.length == 0) {
                        helper.myAlert("数据表中没有找商品类目，请重新上传!");
                        $scope.odj = null;
                        return false;
                    } else {
                        $scope.tim = 10;
                        helper.myTip("上传中,请勿操作!", $event.currentTarget, null, $scope.tim);
                        $scope.cateAry = {};
                        async.mapSeries(cateData, function(data, callback) {
                            if (data) {
                                var query = {
                                    page_size: 100,
                                    query: {
                                        store_id: $scope.store,
                                        name: data
                                    }
                                };
                                dataService.categoryGet(query).then(function(r) {
                                    if (r.itemcats[0]) {
                                        $scope.cateAry[data] = r.itemcats[0].cid;
                                        callback(null);
                                    } else {
                                        dataService.categoryGet({
                                            query: {
                                                level: 1
                                            }
                                        }).then(function(r) {
                                            if (r.itemcats && r.itemcats[0].cid) {
                                                dataService.categoryAdd({
                                                    name: data,
                                                    store_id: $scope.store,
                                                    parent_cid: r.itemcats[0].cid
                                                }).then(function(r) {
                                                    if (r.cid) {
                                                        $scope.cateAry[data] = r.cid;
                                                        callback(null);
                                                    } else {
                                                        $scope.cateAry[data] = 0;
                                                        callback(null);
                                                    }
                                                });
                                            } else {
                                                $scope.cateAry[data] = 0;
                                                callback(null);
                                            }
                                        });
                                    }
                                })
                            } else {
                                callback(null);
                            }
                        }, function(e, r) {
                            $scope.tim = 0;
                            $scope.savetype = 1;
                            $scope.records = $scope.newData;
                        });
                    }
                }

                //保存操作
                $scope.save = function($event) {
                    //找到价格
                    $scope.ti = 30;
                    $scope.info = 0;
                    helper.myTip("保存中,请勿操作!", $event.currentTarget, null, $scope.ti);
                    $scope.value = 10;
                    $scope.progress();
                    async.mapSeries($scope.records, function(data, callback) {
                        console.error("data", data);

                        if (data.skus) {
                            $scope.num = 0;
                            $scope.up = 0;
                            dataService.itemGet({
                                query: {
                                    outer_id: data.outer_id,
                                    store_id: $scope.store
                                }
                            }).then(function(list) {
                                if (list.items[0]) {
                                    var item = list.items[0];
                                    console.error("item", item);
                                    $scope.info = $scope.info + 1;
                                    data.status = 3;
                                    data.item_id = item.item_id;
                                    sku.doFinishSkuData(data.skus, item.item_id, function(skusData) {
                                        for (var i = 0; i < skusData.length; i++) {
                                            for (var j = 0; j < item.skus.length; j++) {
                                                if ((skusData[i].sku_outer_id == item.skus[j].sku_outer_id) && (skusData[i].sku_properties == item.skus[j].sku_properties)) {
                                                    skusData[i].sku_id = item.skus[j].sku_id;
                                                    skusData[i].item_id = item.skus[j].item_id;
                                                }
                                            }
                                        }
                                        data.skus = skusData;
                                        console.error("1data.skus", data.skus);
                                        callback(null);
                                    });
                                } else {
                                    var temporary_item_id = Math.round(Math.random() * 9999 + 1000000);
                                    console.error("temporary_item_id", temporary_item_id);
                                    // return false;
                                    //第一次插入不存在的数据，出现sku_type sku_value 两个表只有一条记录   上传二次才会出现两个记录
                                    sku.doFinishSkuData(data.skus, temporary_item_id, function(skusData) {
                                        data.skus = skusData;
                                        callback(null);
                                    });
                                }
                            });
                        } else {
                            callback(null);
                        }
                    }, function(e, r) {
                        $scope.value = 50;
                        console.error("$scope.records", $scope.records);
                        $scope.derItemAdd();
                    });
                }

                $scope.randomNumber = function() {
                    var now = new Date()
                    var month = now.getMonth() + 1
                    var day = now.getDate()
                    var hour = now.getHours()
                    var minutes = now.getMinutes()
                    var seconds = now.getSeconds()
                    month = this.setTimeDateFmt(month)
                    hour = this.setTimeDateFmt(hour)
                    minutes = this.setTimeDateFmt(minutes)
                    seconds = this.setTimeDateFmt(seconds)
                    return now.getFullYear().toString() + month.toString() + day + hour + minutes + seconds + (Math.round(Math.random() * 89 + 100)).toString()
                }

                //获取体验二维码
                $scope.progress = function() {
                    var qrcodeWin = $.alert({
                        backdrop: "static",
                        keyboard: false,
                        title: '{{"导入进度"|translate}}',
                        body: '<div> <div style="height:180px" ><div class="sui-progress progress-info progress-striped active"><div style="width: {{value}}%;" class="bar"></div></div><span ng-show="value==100">操作完成，请关闭弹窗！</span></div><span  class="sui-form sui-form pull-right" ng-show="value==100"><button class="sui-btn btn-primary" ng-click="rmAlert()">关闭</button></span></div>',
                        // okBtn: '{{"关闭"|translate}}',
                        closeBtn: false,
                        hasfoot: false,
                        transition: true,
                        // height: 100,
                        // width: 'small',
                        show: function(e) {
                            $compile($(e.currentTarget).contents())($scope);
                        },
                        okHide: function(e) {},
                        shown: function(e) {}
                    });
                }

                $scope.rmAlert = function() {
                    $scope.ti = 0;
                    $scope.type = 1;
                    $scope.obj = null;
                    rmAlert();
                }

                $scope.derItemAdd = function() {
                    $scope.suc = 0;
                    $scope.err = 0;
                    async.mapSeries($scope.records, function(data, callback) {
                        data.category_id = $scope.cateAry[data.category];
                        if (data.status != 3 && !data.item_id) {
                            dataService.itemAdd(data).then(function(r) {
                                if (r.Msg) {
                                    $scope.err = $scope.err + 1;
                                    data.status = "2";
                                    callback(null);
                                } else {
                                    $scope.suc = $scope.suc + 1;
                                    $scope.num = $scope.num + 1;
                                    data.status = "1";
                                    sku.updateSkuTypeItemid(data.skus, r.item_id, function() {
                                        callback(null);
                                    });
                                }
                            })
                        } else {
                            // console.error("----------------data", data);
                            $scope.itemUpdateFront(data, function() {
                                dataService.itemUpdate(data).then(function(r) {
                                    if (!r.Msg) {
                                        data.status = "4";
                                        $scope.up = $scope.up + 1;
                                        callback(null);
                                    } else {
                                        callback(null);
                                    }
                                });
                            })
                        }
                    }, function(e, r) {
                        console.error("numnum", $scope.num);
                        $scope.value = 100;
                        $scope.odj = 1;
                        $scope.getapiWork();
                    });
                }
                $scope.itemUpdateFront = function(itemsData, callback) {
                    async.mapSeries(itemsData.skus, function(data, cb) {
                            if (!data.sku_id) {
                                var query = {
                                    item_id: itemsData.item_id,
                                    skus: [data]
                                };
                                dataService.itemAdd(query).then(function(r) {
                                    cb(null);
                                });
                            } else {
                                cb(null);
                            }
                        },
                        function(e, d) {
                            if (callback) {
                                callback(itemsData);
                            }
                        }
                    );
                };

                //触发work
                $scope.getapiWork = function() {
                    var query = {
                        content: {
                            type: "item",
                            store_id: $rootScope.store_id,
                        }
                    };
                    dataService.nsqCommonAdd(query).then(function(list) {

                    });
                }

            }],
            link: function(scope, element, attrs, ctrl) {

            }
        }
    }])
})();